/** 实现一个函数重载 */
class HeavyLoad<T = any> {
    public methodMap = new Map();

    public static build<T = any>() {
        return new HeavyLoad<T>();
    }

    /** 新增一个重载函数 */
    public method(fun: (...arg:any[])=>T): HeavyLoad<T>;
    public method(fun: (...arg:any[])=>T,parameterType: Array<string>):HeavyLoad<T>
    public method(fun: (...arg:any[])=>T,parameterType?: Array<string>):HeavyLoad<T> {
        if (parameterType) {
            this.methodMap.set(parameterType.join(""), fun)
        } else {
            this.methodMap.set(fun.length, fun)
        }
        return this;
    }

    public run = (...arg: any[])=>{
        // 去除尾部无效数据
        while (true) {
            let a = arg.pop();
            if (a != undefined) {
                arg.push(a);
                break;
            }
        }
        let fun = this.methodMap.get(arg.map(e => typeof e).join(""))
        if (!fun) {
            fun = this.methodMap.get(arg.length);
        }
        if (!fun) {
            console.log(arg)
            throw new Error("此函数重载不存在");
        }
        return fun(...arg) as T;
    }

    public end():(...arg:any[])=>T{
        return this.run;
    }
}

export = HeavyLoad;